import lupa
# 实例化一个lua解释器
lua = lupa.LuaRuntime()

# 类似于python中的eval，将字符串当成代码来执行
# 同时返回其结果
print(lua.eval("1 + 1"))  # 2


lua_func = lua.eval(
    """
    function (f, str, substr)
        return f(str, substr)
    end
    """
)
print(lua_func(str.find, "hell1o satori", "satori"))  # 6

lua_func1 = lua.eval(
    """
    function (str)
        return string.reverse(str)
    end
    """
)
print(lua_func1("hell1o satori"))  # 6

lua_fuc_text = 'function (str) \n \t  return string.reverse(str)  end'

lua_func2 = lua.eval(lua_fuc_text)

print(lua_func2("hell1o satori"))  # 6

max = '''
        function (num1, num2)

        if (num1 > num2) then
        result = num1;
        else
        result = num2;
        end

        return result;
        end
    '''
lua_func2 = lua.eval(max)

print(lua_func2(8, 6))  # 6

try:
    print(lua.eval("2 ** 2"))
except Exception as e:
    # error loading code: [string "<python>"]:1: unexpected symbol near '*'
    print(e)

# lua中的幂运算使用的是 ^
print(lua.eval("2 ^ 5"))  # 32

# 如果就想使用python的语法的话
print(lua.eval("python.eval('2 ** 5')"))  # 32

# ['a', 'b', 'c', '1', '2', '3']
print(lua.eval("python.builtins.list('abc123')"))
